//
//  XLCommitDataController.m
//  XiangLove
//
//  Created by 宋振 on 2018/8/7.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLCommitDataController.h"
#import <SVProgressHUD.h>
//显示cell
#import "XLCommitDataCell.h"

//区头图片
#import "XLCommitPictureView.h"

//语音界面
#import "XLCommitRecorderView.h"

//跳转界面
#import "XLCommitInputController.h"
#import "XLVideoSetController.h"

//地区
#import "BMHAreaPickView.h"

//年龄
#import "BMHUserPickerView.h"

//上传图片
#import "BMHPhotoPickManager.h"
#import "BMHPhotoPickManager.h"
#import "UIImage+Clip.h"
#import "TQAFNetworkDownload.h"

//储存图片数据
#import "XLCommitVideoSetModel.h"
#import "XLCommitGetUserModel.h"

#import "XLVideoPlayVC.h"
#import "XLRecordTool.h"


#import "HelpTool.h"
#import "NSString+Ext.h"
#import "MBProgressHUD.h"
#import "ZYQAssetPickerController.h"
#import "SBCaptureToolKit.h"
#import "SFHFKeychainUtils.h"
#import "TXYUploadManager.h"
#import "UILabel+dynamicSize.h"
#define  SIGN_URL @"http://test.m.interface.baomihua.com/weise/WSVideoAction.ashx?action=sign&bucketName=bucket"
#import <QCloudCore.h>
#import <QCloudCOSXML/QCloudCOSXML.h>
#import "XLAlertCommitView.h"







@interface XLCommitDataController ()<UITableViewDelegate,UITableViewDataSource,XLCommitRecorderViewDelegate,XLCommitPictureViewDelegate>

//界面显示容器
@property (nonatomic, strong) UITableView *  tableView;

/**
 数据源
 */
@property (nonatomic, strong) NSMutableArray *  dataSources;

//弹窗容器
@property (nonatomic, strong) UIWindow *  window;

/**
 地区选择列表
 */
@property (nonatomic, strong) BMHAreaPickView *  areaPickerView;

/**
 年龄选择列表
 */
@property (nonatomic, strong) BMHUserPickerView *  userPickerView;

//语音界面
@property (nonatomic, strong) XLCommitRecorderView *recorderView;

//图片列表
@property (nonatomic, strong) NSMutableArray *  pictures;

//本界面数据
@property (nonatomic, strong) XLCommitGetUserModel *  getUserModel;

@property (nonatomic,strong) TXYUploadManager   *uploadFileManager;

@property (nonatomic, strong) TXYFileUploadTask *  uploadFileTask;

//签名
@property (nonatomic,copy  ) NSString           *sign;

//提示
@property (nonatomic, strong) XLAlertCommitView *  xlAlertVc;

@property (strong, nonatomic) HXPhotoManager *manager;

@property (strong, nonatomic) HXDatePhotoToolManager *toolManager;

@end

@implementation XLCommitDataController
{
    //年龄列表
    NSMutableArray *ageList;
    
    //图片列表
    NSMutableArray *pics;
    
    NSString *bucket;
    
    NSString *appId;
    
    NSString *persistenceId;
    
    TXYFileUploadTaskRsp *fileRsp;
    
    NSString *upLoadVoiceUrl;
    
    CGFloat headerHeight;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"编辑资料";
    
    headerHeight = (ScreenWidth-40-3*7)/4+35+30;
    
    [self showBackButton:^{
        
        if (self.isCommit) {
            
            //如果是首页进来的设置信息，如果是女则需要设置两张图片
            if (self.pictures.count <= 1) {
                
                [self setAlertAction];
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
        
    }];
    
    
    
    /**
     主要界面UI绘制
     */
    [self setCustomeView];
    
    /**
     绘制右边按钮
     */
    [self setNavigationBarRightButton];
    
    /**
     请求数据
     */
    [self requestSource];
    
}

//设置弹窗显示
- (void)setAlertAction
{
    //语音
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.windowLevel = UIWindowLevelAlert+1;
    self.window.backgroundColor = [UIColor clearColor];
    [self.window makeKeyAndVisible];
    
    self.xlAlertVc = [[XLAlertCommitView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    [self.window addSubview:self.xlAlertVc];
    
    @weakify(self)
    self.xlAlertVc.clickButton = ^{
        @strongify(self)
                   
        [self.xlAlertVc removeFromSuperview];
        [self.window resignKeyWindow];
        self.window = nil;
        self.xlAlertVc = nil;
    };
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    if ([[XLRecordTool shareRecordTool].player isPlaying]) {
        [[XLRecordTool shareRecordTool].player stop];
    }
    
}


#pragma mark     - - - 设置主要界面显示 - - -

/**
 设置导航栏右边按钮显示
 */
- (void)setNavigationBarRightButton
{
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 45, 45)];
    [rightBtn setTitle:@"保存" forState:(UIControlStateNormal)];
    [rightBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [rightBtn addTarget:self action:@selector(onClickedSaveBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIBarButtonItem *rightBtnItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightBtnItem;
    self.navigationItem.rightBarButtonItem.customView.hidden = YES;
    self.navigationItem.rightBarButtonItem.customView.userInteractionEnabled = YES;
}

/**
 设置主要界面显示
 */
- (void)setCustomeView
{
    //设置界面显示容器
    [self initTableView];
    
    //注册cell
    [self.tableView registerClass:[XLCommitDataCell class] forCellReuseIdentifier:NSStringFromClass([XLCommitDataCell class])];
    
}



#pragma mark    - - - 数据请求 - - -

/**
 数据请求
 */
- (void)requestSource
{
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/Api/v2/UserInfo/GetUpdateUserInfo" parameters:@{@"userId":[XLAccountManager shareInstance].model.Id} resultClass:[XLCommitGetUserModel class]] subscribeNext:^(id x) {
        
        self.getUserModel = [[XLCommitGetUserModel alloc] init];
        self.getUserModel = x;
        
        //初始化辅助变量
        [self initTools];
        
        [self.tableView reloadData];
        
    } error:^(NSError *error) {
        
        NSLog(@"请求getUserModel不成功");
        //初始化辅助变量
        [self initTools];
        [self.tableView reloadData];
        
    }];
    
    
}




#pragma mark    -   -   - 设置UITableView -   -   -
- (void)initTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStyleGrouped)];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.bounces = NO;
    self.tableView.backgroundColor = RGB(243, 243, 243);
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}



#pragma mark    -   -   -   Init Tools  -   -   -
/**
 初始化辅助变量
 */
- (void)initTools
{
    //初始化标题信息等
    NSArray *nameArray = @[@[@"昵称",@"年龄"],@[@"个人介绍",@"城市"],@[@"语音签名",@"视频集"]];
    NSMutableArray *tempDataSource = [NSMutableArray arrayWithCapacity:1];
    
    for (NSInteger i = 0; i < nameArray.count; i ++) {
        
        NSArray *array = nameArray[i];
        
        //temp
        NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:1];
        
        for (NSInteger k = 0; k < array.count; k ++) {
            
            CommitDataModel *model = [[CommitDataModel alloc] init];
            
            model.title = array[k];
            
            model.isSpeech = NO;
            
            //获取信息
            
            //获取名称
            if (i == 0 && k == 0) {
                model.descrip = K_DEFULT(self.getUserModel.NickName);
            }else if (i == 0 && k == 1){
                model.descrip = [NSString stringWithFormat:@"%ld",self.getUserModel.Age];
            }else if (i == 1 && k == 0){
                model.descrip = K_DEFULT(self.getUserModel.Introduction);
            }else if (i == 1 && k == 1){
                model.descrip = K_DEFULT(self.getUserModel.HostCity);
            }else if (i == 2 && k == 0) {
                model.isSpeech = YES;
                
                NSArray *tempArray = self.getUserModel.VoiceSignatures;
                
                if (tempArray && tempArray.count > 0) {
                    
                    NSDictionary *dic = tempArray[0];
                    
                    model.recorderUrl = K_DEFULT(dic[@"PlayUrl"]);
                    model.second = [NSString stringWithFormat:@"%@",dic[@"PlayCost"]];
                    model.descrip = [NSString stringWithFormat:@"%@",dic[@"PlayCost"]];
                    
                }
                
            }else if (i == 2 && k == 1){
                model.descrip = [NSString stringWithFormat:@"%ld",self.getUserModel.VideoNums];
            }
            
            [tempArray addObject:model];
            
        }
        
        if (self.dataSources.count > 0) {
            [self.dataSources removeAllObjects];
        }
        
        [tempDataSource addObject:tempArray];
        
    }
    
    if (self.dataSources.count > 0) {
        [self.dataSources removeAllObjects];
    }
    
    self.dataSources = [tempDataSource mutableCopy];
    
    //年龄
    
    if (ageList.count > 0) {
        ageList = nil;
    }
    
    ageList = [NSMutableArray arrayWithCapacity:1];
    
    for (NSInteger i = 18; i < 100; i ++) {
        [ageList addObject:[NSString stringWithFormat:@"%ld",i]];
    }
    
    if (self.pictures.count > 0) {
        [self.pictures removeAllObjects];
    }
    
    [self.pictures addObjectsFromArray:self.getUserModel.Photos];
    
    [self initUpLodeVide];
    
}

#pragma mark    - - - 设置头像标志 - - -
- (void)setHeaderImage:(NSIndexPath *)indexPath
{
    
}

/**
 点击保存拖动后的图片顺序
 */
- (void)onClickedSaveBtn:(UIButton *)button
{
    self.navigationItem.rightBarButtonItem.customView.hidden = YES;
    
    [[TQAFNetworkDownload shareTQAFNetwork] TQAFNetworkHttpRequestJsonStyle:@"POST" Url:@"/Api/v2/UserInfo/UpdateUserPhotos" parameter:@{@"Photos":self.pictures} success:^(id responseObject) {
        
        if (responseObject) {
            
            
            
        }
        
    } failt:^(NSError *error) {
        
        [HelpTool startTipViewWithText:@"保存失败" duration:1 type:(kTipViewTypeNone)];
        self.navigationItem.rightBarButtonItem.customView.hidden = NO;
        
    }];
}

#pragma mark    - - - 编辑图片（区头）代理 - - -
- (void)commitPictureRefreshSource:(NSMutableArray *)array isRefresh:(BOOL)fresh isMove:(BOOL)isMoveItem
{
    
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:1];
    
    //获取所有图片
    for (NSInteger i = 0; i < array.count; i ++) {
        
        NSDictionary *tempDic = array[i];
        
        NSString *url = K_DEFULT(tempDic[@"Url"]);
        NSInteger userId = [NSString stringWithFormat:@"%@",tempDic[@"UserId"]].integerValue;
        NSInteger OrderId = [NSString stringWithFormat:@"%@",tempDic[@"OrderId"]].integerValue;
        NSInteger IsHeadImage = [NSString stringWithFormat:@"%@",tempDic[@"IsHeadImage"]].integerValue;
        NSInteger Id = [NSString stringWithFormat:@"%@",tempDic[@"Id"]].integerValue;
        
        NSDictionary *addDic = @{
                                 @"UserId":@(userId),
                                 @"Url":K_DEFULT(url),
                                 @"IsHeadImage":@(IsHeadImage),
                                 @"Id":@(Id)
                                 };
        
        [arr addObject:addDic];
    }
    
    if (self.pictures.count > 0) {
        
        [self.pictures removeAllObjects];
        
    }
    
    self.pictures = [arr mutableCopy];
    
    if (isMoveItem) {
        //显示保存按钮
        self.navigationItem.rightBarButtonItem.customView.hidden = NO;
        self.navigationItem.rightBarButtonItem.customView.userInteractionEnabled = YES;
    }else{
        if (fresh) {
            [self.tableView reloadData];
        }
    }
    
}

//更换图片代理
- (void)commitPicturesReplaceImageWithIndexPath:(NSIndexPath *)indexPath selectIndex:(NSInteger)selectIndex
{
    [self selectCamareOrAlbulm:indexPath selectIndex:selectIndex];
}

//更换图片
- (void)selectCamareOrAlbulm:(NSIndexPath *)indexPath selectIndex:(NSInteger)selectIndex
{
    
    if (selectIndex == 2) {
        
        [[BMHPhotoPickManager shareInstance] pickFromAlbumInController:self successHandler:^(UIImage *image) {
            [self updateServerImageDataWithImage:image indexPath:indexPath];
            
        } cancelHandler:^{
            
            NSLog(@"获取图片失败！");
            
        }];
        
    }else if (selectIndex == 3){
        
        [[BMHPhotoPickManager shareInstance] pickFromCameraInController:self successHandler:^(UIImage *image) {
            
            [self updateServerImageDataWithImage:image indexPath:indexPath];
            
        } cancelHandler:^{
            
            NSLog(@"获取图片失败！");
            
        }];
        
    }
    
    
}

//拖动之后更新数据，显示保存按钮，如果保存，则保存当前顺序
- (void)commitPictureMoveImageWithFromIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    [self.pictures exchangeObjectAtIndex:indexPath.row withObjectAtIndex:toIndexPath.row];
    
    //显示保存按钮 保存之后 再隐藏按钮
}

- (void)updateServerImageDataWithImage:(UIImage *)image indexPath:(NSIndexPath *)indexPath
{
    [self.navigationItem.rightBarButtonItem setEnabled:NO];
    
    [XLHTTPSessionManager upLoadImageFileWithImage:image Progress:^(NSNumber *progress) {
        BMHLog(@"%@", progress);
        
    } Success:^(id success) {
        
        
        NSDictionary *avatarDic = [self.pictures objectAtIndex:indexPath.row];
        
        //获取本地图片
        NSString *pic = [NSString stringWithFormat:@"%@",(NSString *)success];
        
        NSDictionary *dic = @{
                              @"UserId":K_DEFULT([XLAccountManager shareInstance].model.Id),
                              @"Url":K_DEFULT(pic),
                              @"IsHeadImage":@([NSString stringWithFormat:@"%@",avatarDic[@"IsHeadImage"]].integerValue)
                              };
        
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:1];
        
        //获取所有图片
        for (NSInteger i = 0; i < self.pictures.count; i ++) {
            
            NSDictionary *tempDic = self.pictures[i];
            
            NSString *url = K_DEFULT(tempDic[@"Url"]);
            NSInteger userId = [NSString stringWithFormat:@"%@",tempDic[@"UserId"]].integerValue;
            NSInteger OrderId = [NSString stringWithFormat:@"%@",tempDic[@"OrderId"]].integerValue;
            NSInteger IsHeadImage = [NSString stringWithFormat:@"%@",tempDic[@"IsHeadImage"]].integerValue;
            NSInteger Id = [NSString stringWithFormat:@"%@",tempDic[@"Id"]].integerValue;
            
            NSDictionary *addDic = @{
                                     @"UserId":@(userId),
                                     @"Url":K_DEFULT(url),
                                     @"IsHeadImage":@(IsHeadImage),
                                     @"Id":@(Id)
                                     };
            
            [arr addObject:addDic];
        }
        
        [arr replaceObjectAtIndex:indexPath.row withObject:dic];
        
        //上传服务器
        [self updatePictureToServerWithPictures:arr];
        
        
    } Failure:^(id error) {
        
    }];
}

#pragma mark    - - - 上传图片方法 - - -
- (void)updateImage{
    [[BMHPhotoPickManager shareInstance] pickFromCustomViewInController:self allowEditing:YES successHandler:^(UIImage *image) {
       

        [self.navigationItem.rightBarButtonItem setEnabled:YES];

        [XLHTTPSessionManager upLoadImageFileWithImage:image Progress:^(NSNumber *progress) {
            BMHLog(@"%@", progress);

        } Success:^(id success) {

            if (self.pictures.count >= 8) {

                NSLog(@"图片已经超过八张！");

            }

            //获取本地图片
            NSString *pic = [NSString stringWithFormat:@"%@",(NSString *)success];

            NSDictionary *dic = @{
                                  @"UserId":K_DEFULT([XLAccountManager shareInstance].model.Id),
                                  @"Url":K_DEFULT(pic),
                                  @"IsHeadImage":@0
                                  };

            NSMutableArray *arr = [NSMutableArray arrayWithCapacity:1];

            //获取所有图片
            for (NSInteger i = 0; i < self.pictures.count; i ++) {

                NSDictionary *tempDic = self.pictures[i];

                NSString *url = K_DEFULT(tempDic[@"Url"]);
                NSInteger userId = [NSString stringWithFormat:@"%@",tempDic[@"UserId"]].integerValue;

                NSInteger IsHeadImage = [NSString stringWithFormat:@"%@",tempDic[@"IsHeadImage"]].integerValue;
                NSInteger Id = [NSString stringWithFormat:@"%@",tempDic[@"Id"]].integerValue;

                NSDictionary *addDic = @{
                                         @"UserId":@(userId),
                                         @"Url":K_DEFULT(url),
                                         @"IsHeadImage":@(IsHeadImage),
                                         @"Id":@(Id)
                                         };

                [arr addObject:addDic];
            }

            [arr addObject:dic];

            //上传服务器
            [self updatePictureToServerWithPictures:arr];


        } Failure:^(id error) {

        }];

    } cancelHandler:^{

    }];
    
}

#pragma mark    - - - 上传图片 - - -

- (void)updatePictureToServerWithPictures:(NSMutableArray *)pictures
{
    [[TQAFNetworkDownload shareTQAFNetwork] TQAFNetworkHttpRequestJsonStyle:@"POST" Url:@"/Api/v2/UserInfo/UpdateUserPhotos" parameter:@{@"Photos":pictures} success:^(id responseObject) {
        
        if (responseObject) {
            
            if (self.pictures.count > 0) {
                [self.pictures removeAllObjects];
            }
            
            self.pictures = [pictures mutableCopy];
            
            NSLog(@"上传图片成功");
            [self.tableView reloadData];
            
        }
        
    } failt:^(NSError *error) {
        
        NSLog(@"上传图片失败");
        
    }];
}

#pragma mark    - - - 上传信息 - - -

- (void)updateUserInfoWithDic:(NSDictionary *)dic
{
    [[[XLHTTPSessionManager sharedManager] XLV2POST:@"Api/v2/UserInfo/UpdateUserInfo" parameters:dic resultClass:nil] subscribeNext:^(id x) {
        
        NSLog(@"修改成功");
        [self.tableView reloadData];
        
    } error:^(NSError *error) {
        
        NSLog(@"修改失败");
        
    }];
}








#pragma mark    - - - 设置UITableView代理和数据源

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSources.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XLCommitDataCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([XLCommitDataCell class]) forIndexPath:indexPath];
    
    //取出section所对应的数据
    NSMutableArray *array = self.dataSources[indexPath.section];
    
    //取出每个section中的数据
    CommitDataModel *model = array[indexPath.row];
    
    
    cell.model = model;
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        XLCommitPictureView *header = [[XLCommitPictureView alloc] init];
        
        header.videos = [self.pictures copy];
        header.model = self.getUserModel;
        header.delegate = self;
        
        headerHeight = [header getHeaderHeight];
        
        header.refreshPictureView = ^(NSIndexPath *indexPath, BOOL isHeaderImg) {
            
            //设置头像标志
            
            [self updateImage];
            
        };
        
        return header;
    }
    
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        
        if (self.pictures.count + 1 > 4) {
            return 240;
        }
        
        //cell的宽高(ScreenWidth-40-3*7)/4 + 下方标题高度 35 + 间隙
        return (ScreenWidth-40-3*7)/4+35+30;
        
        //        return headerHeight;
    }
    
    return 0.1;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        
        XLCommitInputController *inputVc = [[XLCommitInputController alloc] init];
        inputVc.style = 1;
        inputVc.placehoder = K_DEFULT(self.getUserModel.NickName).length>0 ? self.getUserModel.NickName : @"输入昵称...";
        inputVc.model = self.getUserModel;
        
        inputVc.editTextBlock = ^(NSString *text) {
            
            //            [self setSourceWithTitle:@"昵称" descrip:text indexPath:indexPath];
            [self requestSource];
            
        };
        
        [self.navigationController pushViewController:inputVc animated:YES];
        
    }else if (indexPath.section == 0 && indexPath.row == 1){
        
        //年龄选择
        [self showUserPickerView:ageList Row:indexPath];
        
    }else if (indexPath.section == 1 && indexPath.row == 0){
        
        XLCommitInputController *inputVc = [[XLCommitInputController alloc] init];
        inputVc.style = 2;
        inputVc.placehoder = K_DEFULT(self.getUserModel.Introduction).length > 0 ? self.getUserModel.Introduction : @"输入个人介绍...";
        inputVc.model = self.getUserModel;
        
        inputVc.editTextBlock = ^(NSString *text) {
            
            //            [self setSourceWithTitle:@"个人介绍" descrip:text indexPath:indexPath];
            [self requestSource];
            
        };
        
        [self.navigationController pushViewController:inputVc animated:YES];
        
    }else if (indexPath.section == 1 && indexPath.row == 1){
        
        //选择地区
        [self showAreaPickView];
        
    }else if (indexPath.section == 2 && indexPath.row == 0){
#pragma mark ---  录制语音并上传
        //语音
        self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        self.window.windowLevel = UIWindowLevelAlert+1;
        [self.window makeKeyAndVisible];
        
        
        if (!self.recorderView) {
            self.recorderView = [[XLCommitRecorderView alloc] initWithFrame:self.window.bounds];
            self.recorderView.delegate = self;
            [self.window addSubview:self.recorderView];
        }else{
            [self.window addSubview:self.recorderView];
        }
        
        [self.recorderView animationView];
        
    }else if (indexPath.section == 2 && indexPath.row == 1){
        
        //视频集
        XLVideoSetController *videoSetVc = [[XLVideoSetController alloc] init];
        
        videoSetVc.userId = [NSString stringWithFormat:@"%ld",self.getUserModel.UserId];
        
        videoSetVc.isRefresh = ^(BOOL refresh) {
            if (refresh) {
                [self requestSource];
            }
        };
        
        [self.navigationController pushViewController:videoSetVc animated:YES];
        
    }
}




#pragma mark        - - - XLCommitRecorderViewDelegate - - -

//取消界面显示
- (void)commitRecorderClickDestroyView
{
    [self.window resignKeyWindow];
    self.window = nil;
}

//上传
- (void)commitRecorderClickSuccessRecorderWithUrl:(NSString *)url andTimeSecond:(NSInteger)second
{
    //上传语音之后操纵事件
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:2];
    
    CommitDataModel *model = [[CommitDataModel alloc] init];
    model.title = @"语音签名";
    model.descrip = [NSString stringWithFormat:@"%ld",second];
    model.isSpeech = YES;
    model.recorderUrl = url;
    model.second = [NSString stringWithFormat:@"%ld",second];
    
    NSMutableArray *tempArray = [self.dataSources[indexPath.section] mutableCopy];
    
    
    
    [tempArray replaceObjectAtIndex:indexPath.row withObject:model];
    
    [self.dataSources replaceObjectAtIndex:indexPath.section withObject:tempArray];
    
    [self.tableView reloadData];
    
    [self.window resignKeyWindow];
    self.window = nil;
    
    
    
    //校验URL是否存在
    NSFileManager *defalt = [NSFileManager defaultManager];
    
    if (![defalt fileExistsAtPath:url]) {
        NSLog(@"文件不存在");
    }else{
        upLoadVoiceUrl = url;
        
        [self uploadVideoWihtVideoPath:url second:second];
    }
    
    
    
    
}









#pragma mark    -   -   - 懒加载 - -   -

//数据源
- (NSMutableArray *)dataSources
{
    if (!_dataSources) {
        self.dataSources = [NSMutableArray arrayWithCapacity:1];
    }
    
    return _dataSources;
}

//图片列表
- (NSMutableArray *)pictures
{
    if (!_pictures) {
        self.pictures = [NSMutableArray arrayWithCapacity:1];
    }
    
    return _pictures;
}

- (HXPhotoManager *)manager {
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhotoAndVideo];
        _manager.configuration.singleSelected = YES;
        _manager.configuration.albumListTableView = ^(UITableView *tableView) {
        };
        _manager.configuration.singleJumpEdit = YES;
        _manager.configuration.movableCropBox = YES;
        _manager.configuration.movableCropBoxEditSize = YES;
        _manager.configuration.albumShowMode = HXPhotoAlbumShowModePopup;
        _manager.configuration.movableCropBoxCustomRatio = CGPointMake(1, 1);
    }
    return _manager;
}

- (HXDatePhotoToolManager *)toolManager {
    if (!_toolManager) {
        _toolManager = [[HXDatePhotoToolManager alloc] init];
    }
    return _toolManager;
}


#pragma mark        - - - 设置显示地区选择 - - -

- (void)showAreaPickView {
    if (self.areaPickerView == nil) {
        self.areaPickerView = [[BMHAreaPickView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        [[UIApplication sharedApplication].keyWindow addSubview:self.areaPickerView];
        [self.areaPickerView show];
        @weakify(self);
        [self.areaPickerView.dismissSignal subscribeNext:^(id x) {
            @strongify(self);
            [self.areaPickerView removeFromSuperview];
            self.areaPickerView = nil;
        }];
        
        [self.areaPickerView.sureSignal subscribeNext:^(NSString *address) {
            @strongify(self);
            BMHLog(@"%@", address);
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:1 inSection:1];
            
            if (indexPath.section == 1 && indexPath.row == 1) {
                
                [self setSourceWithTitle:@"城市" descrip:address indexPath:indexPath];
                
                //上传信息
                NSDictionary *dic = dic = @{
                                            @"UserId":K_DEFULT([XLAccountManager shareInstance].model.Id),
                                            @"NickName":K_DEFULT(self.detailModel.NickName),
                                            @"Age":[NSString stringWithFormat:@"%@",self.detailModel.Age],
                                            
                                            @"HostCity":K_DEFULT(address),
                                            @"Introduction":K_DEFULT(self.detailModel.Introduction)
                                            };
                
                [self updateUserInfoWithDic:dic];
                
                
            }
        }];
    }
}

- (void)showUserPickerView:(NSArray *)array Row:(NSIndexPath *)indexPath{
    if (self.userPickerView == nil) {
        self.userPickerView = [[BMHUserPickerView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        self.userPickerView.proTitleList = array;
        [[UIApplication sharedApplication].keyWindow addSubview:self.userPickerView];
        [self.userPickerView show];
        @weakify(self);
        [self.userPickerView.dismissSignal subscribeNext:^(id x) {
            @strongify(self);
            [self.userPickerView removeFromSuperview];
            self.userPickerView = nil;
        }];
        [self.userPickerView.sureSignal subscribeNext:^(NSString *str) {
            @strongify(self);
            BMHLog(@"keyi %@", str);
            
            if (indexPath.section == 0 && indexPath.row == 1) {
                
                [self setSourceWithTitle:@"年龄" descrip:str indexPath:indexPath];
                
                //上传信息
                
                NSDictionary *dic = dic = @{
                                            @"UserId":K_DEFULT([XLAccountManager shareInstance].model.Id),
                                            @"NickName":K_DEFULT(self.detailModel.NickName),
                                            @"Age":K_DEFULT(str),
                                            @"HostCity":K_DEFULT(self.detailModel.HostCity),
                                            @"Introduction":K_DEFULT(self.detailModel.Introduction)
                                            };
                
                [self updateUserInfoWithDic:dic];
                
            }
            
        }];
    }
}


#pragma mark    - - - 辅助方法 - - -

//设置更新数据
- (void)setSourceWithTitle:(NSString *)title descrip:(NSString *)descrip indexPath:(NSIndexPath *)indexPath
{
    CommitDataModel *model = [[CommitDataModel alloc] init];
    model.title = K_DEFULT(title);
    model.descrip = K_DEFULT(descrip);
    model.isSpeech = NO;
    
    NSArray *array = self.dataSources[indexPath.section];
    
    NSMutableArray *tempArray = [NSMutableArray arrayWithArray:array];
    
    
    
    [tempArray replaceObjectAtIndex:indexPath.row withObject:model];
    
    [self.dataSources replaceObjectAtIndex:indexPath.section withObject:tempArray];
    
    [self.tableView reloadData];
}


//上传方法
-(void)uploadVideoWihtVideoPath:(NSString *)path second:(NSInteger)second
{
    
    NSString *token = [[HelpTool getIOSuuid] substringToIndex:7];
    //    self.fileName = [NSString stringWithFormat:@"%@_%@", token, self.videoName];
    
    NSDate * date = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMddHHmmss"];
    NSString *locationString = [dateformatter stringFromDate:date];
    
    NSString *lastStr = [path lastPathComponent];
    
    NSString *voiceName = [NSString stringWithFormat:@"%@_%@%@",token,locationString,lastStr];
    
    
    QCloudCOSXMLUploadObjectRequest *objectRequest = [[QCloudCOSXMLUploadObjectRequest alloc] init];
    
    objectRequest.object = voiceName;
    objectRequest.bucket = bucket;
    objectRequest.body = [NSData dataWithContentsOfFile:path];
    
    [objectRequest setSendProcessBlock:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
        
        NSLog(@"111111111111111");
        
    }];
    
    
    [objectRequest setFinishBlock:^(QCloudUploadObjectResult *result, NSError *error) {
        NSLog(@"2222222222222222");
        
        if (!error) {
            
            NSString *content = result.location;
            
            @weakify(self)
            [[[XLHTTPSessionManager sharedManager] XLV2POST:@"/api/v2/DynamicVideo/PublishVoiceSign" parameters:@{
                                                                                                                  @"UserId":[XLAccountManager shareInstance].model.Id,
                                                                                                                  @"Title":@"voice",
                                                                                                                  @"Content":K_DEFULT(voiceName),
                                                                                                                  @"PlayCost":@(second)
                                                                                                                  } resultClass:nil] subscribeNext:^(id x) {
                @strongify(self)
                NSLog(@"上传成功！");
                //取出section所对应的数据
                
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:2];
                
                NSMutableArray *array = [self.dataSources[indexPath.section] mutableCopy];
                
                //取出每个section中的数据
                CommitDataModel *model = array[indexPath.row];
                model.recorderUrl = content;
                
                [array replaceObjectAtIndex:indexPath.row withObject:model];
                [self.dataSources replaceObjectAtIndex:indexPath.section withObject:array];
                [self.tableView reloadData];
                
                //                [self requestSource];
                
                
            } error:^(NSError *error) {
                
                NSLog(@"上传失败！");
                
            }];
            
        }
        
        
    }];
    [[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:objectRequest];
    
    
}

-(void)getUploadVidoSign
{
    
    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    //时间戳
    NSString *sTime = [fmt stringFromDate:now];
    NSString *objID = @"0";
    NSString *publicKey = @"BMH2014YDYWB";
    NSString *nat = [NSString stringWithFormat:@"%@%@%@%@",objID, uid, publicKey, sTime];
    nat = [nat md5Encrypt];
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    
    
    
    NSDictionary *cloundSignDic =[NSDictionary dictionaryWithObjectsAndKeys:@"2",@"type",@"dynamic",@"BucketName",uid,@"UserID",locationString,@"Timestamp",nat,@"AppSign", nil];
    
    [BMHHTTPSession GET:@"/MobileInterface/Video/VideoCloud.ashx" paraments:cloundSignDic success:^(id  _Nullable JSON) {
        NSLog(@"云存储签名==========-=-=-----%@", JSON);
        
        self.sign = JSON[@"result"][@"errmsg"];
        
        
    } failure:^(NSError * _Nullable error) {
        
    }];
    
    
}

-(void)initUpLodeVide
{
    
    NSString *token = [[HelpTool getIOSuuid] substringToIndex:7];
    //    self.fileName = [NSString stringWithFormat:@"%@_%@", token, @"voice"];
    
    appId = @"10063237";//10063237
    bucket = @"dynamic"; //上传视频入口：发表动态：bucket=bucket 发红包视频：bucket=tempvideo
    
    persistenceId = @"voiceID";//自定义,唯一,没有限制
    //上传视频总共五步之     第二步 向自己的业务服务器请求 上传image所需要的签名
    [self getUploadVidoSign];
    
    //上传视频总共五步之     第三步: 初始化上传工具
    self.uploadFileManager = [[TXYUploadManager alloc] initWithCloudType:TXYCloudTypeForFile
                                                           persistenceId:persistenceId
                                                                   appId:appId];
}




@end
